package com.newhis.config;

import com.newhis.thread.TraceIdUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@Component
@Order(0)
@WebFilter(urlPatterns = "/**")
public class WebConfig implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            TraceIdUtil.setTraceId(TraceIdUtil.generateTraceId());
            TraceIdUtil.setClientIp(servletRequest.getRemoteAddr());
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            TraceIdUtil.clear();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
